import { BaseClass } from "./BaseClass";

export interface IEMsg {
    msgName: string,    //消息名字
    callback: Function, //消息的回调
    caller: Object,      //调用的当前this
}

/**
 * 自定义事件订阅与发布模块
 */
export class EventMgr extends BaseClass{
    private events_map = {};// {"eventName": [ {func: 回调的函数, caller: 函数里面的this}], "eventName": [], }

    private static _inst: EventMgr;
    public static get inst(): EventMgr {
        if (this._inst == null) {
            this._inst = new EventMgr();
        }

        return this._inst;
    }

    constructor() {
        super()    
        // this.eventMap = new Map()
    }

    /**
     * 
     * @param event_name 事件名字
     * @param caller target
     * @param func 回调
     */
    public AddEventListener(event_name:string, func:Function,caller:Object) {
        if (!this.events_map[event_name]) {
            this.events_map[event_name] = [];
        }

        var event_queue = this.events_map[event_name];
        event_queue.push({
            caller: caller,
            func: func
        });
    }

    /**
     * 
     * @param event_name
     * @param func 
     * @param caller 
     * @returns 
     */
    public RemoveEventListener(event_name: string, func:Function ,caller: Object) {
        if (!this.events_map[event_name]) {
            return;
        }

        var event_queue = this.events_map[event_name];
        for (var i = 0; i < event_queue.length; i++) {
            var obj = event_queue[i];
            if (obj.caller == caller && obj.func == func) {
                event_queue.splice(i, 1);
                break;
            }
        }

        if (event_queue.length <= 0) {
            this.events_map[event_name] = null;
        }
    }

    public Emit(event_name, udata: any = null) {
        if (!this.events_map[event_name]) {
            return;
        }

        var event_queue = this.events_map[event_name];
        for (var i = 0; i < event_queue.length; i++) {
            var obj = event_queue[i];
            obj.func.call(obj.caller, event_name, udata);
        }
    }
}